'use strict';
const Service = require('egg').Service;

class RepairmenService extends Service {
  // 通过账号查找某个维修员
  async findRepairmenByAccount(repairmen_account) {
    const { ctx } = this;
    return await ctx.model.Repairmen.findOne({
      repairmen_account,
    });
  }

  // 添加维修员
  async insertOneRepairmen(data) {
    const ctx = this.ctx;
    return await ctx.model.Repairmen.create({
      repairmen_account: data.account,
      repairmen_password: data.password,
      repairmen_name: data.name,
      add_time: Date.now(),
      repairmen_status: 1,
      identity: 3
    });
  }

  // 验证维修员账号密码
  async authRepairmen(account, password) {
    const repairmen = await this.findRepairmenByAccount(account);
    if (!repairmen) {
      // 查无此人
      return {
        errcode: 1,
        msg: "维修员账号不存在"
      };
    }
    if (repairmen.repairmen_password !== password) {
      // 密码错误
      return {
        errcode: -1,
        msg: "密码错误"
      };
    }
    return {
      errcode: 0,
      msg: "success",
      data: repairmen
    };
  }

  // 查询维修员
  async searchRepairmen(conditions) {
    const ctx = this.ctx;
    const keyword = new RegExp(conditions.keyword, 'i');
    const page = conditions.page || 1;
    const pageSize = conditions.pageSize || 10;
    const query = {
      repairmen_name: { $regex: keyword }
    };

    const [list, total] = await Promise.all([
      ctx.model.Repairmen.find(query)
        .select('-repairmen_password')
        .sort('repairmen_account')
        .skip((page - 1) * pageSize)
        .limit(pageSize),
      ctx.model.Repairmen.find(query).count(),
    ]);

    return {
      list,
      paging: ctx.helper.getPaging(total, pageSize)
    };
  }

  // 修改维修员信息
  async updateRepairmen(data) {
    const { ctx } = this;
    const newData = {
      repairmen_name: data.name
    };
    if (data.password) {
      newData.repairmen_password = data.password;
    }
    await ctx.model.Repairmen.findByIdAndUpdate(data._id, newData);
    return { errcode: 0 };
  }

  // 删除维修员
  async delRepairmen(id) {
    const { ctx } = this;
    await ctx.model.Repairmen.deleteOne({ _id: id });
    return { errcode: 0 };
  }

}

module.exports = RepairmenService;
